<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>接水果</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: #87CEEB;
            touch-action: none;
            overflow: hidden;
        }
        #gameContainer {
            position: relative;
            width: 100vw;
            height: 100vh;
        }
        #gameCanvas {
            width: 100%;
            height: 100%;
        }
        .game-info {
            position: absolute;
            top: 20px;
            left: 0;
            width: 100%;
            display: flex;
            justify-content: space-between;
            padding: 0 20px;
            pointer-events: none;
        }
        #score {
            font-size: 24px;
            color: #fff;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        #restartBtn {
            padding: 8px 20px;
            font-size: 16px;
            background: #ff6b6b;
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            pointer-events: auto;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        #gameOver {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 30px;
            border-radius: 10px;
            text-align: center;
            display: none;
        }
        #gameOver h2 {
            margin-bottom: 15px;
            font-size: 28px;
        }
        #finalScore {
            font-size: 22px;
            margin-bottom: 20px;
        }
        #playAgainBtn {
            padding: 10px 25px;
            font-size: 18px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div id="gameContainer">
    <div class="game-info">
        <div id="score">分数: 0</div>
        <button id="restartBtn">重新开始</button>
    </div>
    <canvas id="gameCanvas"></canvas>
    <div id="gameOver">
        <h2>游戏结束!</h2>
        <div id="finalScore">最终分数: 0</div>
        <button id="playAgainBtn">再来一次</button>
    </div>
</div>

<script>
    (function() {
        const dpr = window.devicePixelRatio || 1;
        const GAME_WIDTH = 320;  // 游戏逻辑宽度
        const GAME_HEIGHT = 480; // 游戏逻辑高度
        const BASKET_WIDTH = 50;
        const BASKET_HEIGHT = 30;
        const ITEM_SIZE = 30;
        const INITIAL_SPEED = 2.5;
        const SPEED_INCREASE = 0.005;
        const SPAWN_RATE = 1200; // 毫秒，减少生成间隔增加难度
        const BOMB_RATE = 0.2;   // 炸弹出现概率

        let canvas = document.getElementById('gameCanvas');
        let ctx = canvas.getContext('2d');
        let score = 0;
        let gameSpeed = INITIAL_SPEED;
        let items = [];
        let basketX = GAME_WIDTH / 2 - BASKET_WIDTH / 2;
        let basketY = GAME_HEIGHT - BASKET_HEIGHT - 20;
        let lastSpawnTime = 0;
        let gameOver = false;
        let touchStartX = 0;
        let basketStartX = 0;

        // 游戏资源
        const IMAGES = {
            basket: null,
            apple: null,
            banana: null,
            orange: null,
            bomb: null
        };

        // 初始化画布
        function initCanvas() {
            const container = document.getElementById('gameContainer');
            const scale = Math.min(
                container.clientWidth / GAME_WIDTH,
                container.clientHeight / GAME_HEIGHT
            );

            canvas.width = GAME_WIDTH * dpr * scale;
            canvas.height = GAME_HEIGHT * dpr * scale;
            canvas.style.width = `${GAME_WIDTH * scale}px`;
            canvas.style.height = `${GAME_HEIGHT * scale}px`;
            ctx.scale(dpr * scale, dpr * scale);
        }

        // 加载图像资源
        function loadImages() {
            return new Promise((resolve) => {
                let loaded = 0;
                const total = Object.keys(IMAGES).length;

                // 创建简单的图形代替实际图片
                IMAGES.basket = createBasketImage();
                IMAGES.apple = createFruitImage('#e74c3c', 0);
                IMAGES.banana = createFruitImage('#f1c40f', Math.PI/2);
                IMAGES.orange = createFruitImage('#e67e22', 0);
                IMAGES.bomb = createBombImage();

                resolve();
            });
        }

        // 创建篮子图像
        function createBasketImage() {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = BASKET_WIDTH * dpr;
            canvas.height = BASKET_HEIGHT * dpr;
            ctx.scale(dpr, dpr);

            ctx.fillStyle = '#8B4513';
            ctx.beginPath();
            ctx.moveTo(0, BASKET_HEIGHT);
            ctx.lineTo(BASKET_WIDTH, BASKET_HEIGHT);
            ctx.lineTo(BASKET_WIDTH - 10, 0);
            ctx.lineTo(10, 0);
            ctx.closePath();
            ctx.fill();

            ctx.fillStyle = '#A0522D';
            ctx.fillRect(0, BASKET_HEIGHT - 5, BASKET_WIDTH, 5);

            return canvas;
        }

        // 创建水果图像
        function createFruitImage(color, rotation) {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = ITEM_SIZE * dpr;
            canvas.height = ITEM_SIZE * dpr;
            ctx.scale(dpr, dpr);

            ctx.save();
            ctx.translate(ITEM_SIZE/2, ITEM_SIZE/2);
            ctx.rotate(rotation);
            ctx.translate(-ITEM_SIZE/2, -ITEM_SIZE/2);

            ctx.fillStyle = color;
            ctx.beginPath();
            ctx.arc(ITEM_SIZE/2, ITEM_SIZE/2, ITEM_SIZE/2 - 2, 0, Math.PI * 2);
            ctx.fill();

            ctx.fillStyle = 'rgba(255,255,255,0.3)';
            ctx.beginPath();
            ctx.arc(ITEM_SIZE/3, ITEM_SIZE/3, ITEM_SIZE/6, 0, Math.PI * 2);
            ctx.fill();

            ctx.restore();
            return canvas;
        }

        // 创建炸弹图像
        function createBombImage() {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            canvas.width = ITEM_SIZE * dpr;
            canvas.height = ITEM_SIZE * dpr;
            ctx.scale(dpr, dpr);

            ctx.fillStyle = '#333';
            ctx.beginPath();
            ctx.arc(ITEM_SIZE/2, ITEM_SIZE/2, ITEM_SIZE/2 - 2, 0, Math.PI * 2);
            ctx.fill();

            ctx.fillStyle = '#555';
            ctx.fillRect(ITEM_SIZE/2 - 2, ITEM_SIZE/4, 4, ITEM_SIZE/2);
            ctx.fillRect(ITEM_SIZE/4, ITEM_SIZE/2 - 2, ITEM_SIZE/2, 4);

            return canvas;
        }

        // 初始化事件监听
        function initEvents() {
            // 触摸事件
            canvas.addEventListener('touchstart', handleTouchStart);
            canvas.addEventListener('touchmove', handleTouchMove);
            canvas.addEventListener('touchend', handleTouchEnd);

            // 鼠标事件（用于调试）
            canvas.addEventListener('mousedown', handleMouseDown);
            canvas.addEventListener('mousemove', handleMouseMove);
            canvas.addEventListener('mouseup', handleMouseUp);

            // 按钮事件
            document.getElementById('restartBtn').addEventListener('click', resetGame);
            document.getElementById('playAgainBtn').addEventListener('click', resetGame);

            // 窗口大小变化事件
            window.addEventListener('resize', initCanvas);
        }

        // 触摸开始处理
        function handleTouchStart(e) {
            if (gameOver) return;
            touchStartX = e.touches[0].clientX;
            basketStartX = basketX;
        }

        // 触摸移动处理
        function handleTouchMove(e) {
            if (gameOver) return;
            e.preventDefault();
            const touchX = e.touches[0].clientX;
            const diffX = touchX - touchStartX;
            const container = document.getElementById('gameContainer');
            const scale = GAME_WIDTH / container.clientWidth;

            basketX = basketStartX + diffX * scale;
            // 限制篮子在屏幕内
            basketX = Math.max(0, Math.min(basketX, GAME_WIDTH - BASKET_WIDTH));
        }

        // 触摸结束处理
        function handleTouchEnd(e) {
            // 不需要额外处理
        }

        // 鼠标按下处理
        function handleMouseDown(e) {
            if (gameOver) return;
            touchStartX = e.clientX;
            basketStartX = basketX;
        }

        // 鼠标移动处理
        function handleMouseMove(e) {
            if (gameOver || touchStartX === 0) return;
            const mouseX = e.clientX;
            const diffX = mouseX - touchStartX;
            const container = document.getElementById('gameContainer');
            const scale = GAME_WIDTH / container.clientWidth;

            basketX = basketStartX + diffX * scale;
            // 限制篮子在屏幕内
            basketX = Math.max(0, Math.min(basketX, GAME_WIDTH - BASKET_WIDTH));
        }

        // 鼠标释放处理
        function handleMouseUp(e) {
            touchStartX = 0;
        }

        // 生成新物品
        function spawnItem(timestamp) {
            if (timestamp - lastSpawnTime > SPAWN_RATE && !gameOver) {
                const isBomb = Math.random() < BOMB_RATE;
                const itemTypes = isBomb ? ['bomb'] : ['apple', 'banana', 'orange'];
                const type = itemTypes[Math.floor(Math.random() * itemTypes.length)];
                const x = Math.random() * (GAME_WIDTH - ITEM_SIZE);

                items.push({
                    x: x,
                    y: -ITEM_SIZE,
                    type: type,
                    speed: gameSpeed + Math.random() * 1,
                    rotation: Math.random() * Math.PI * 2,
                    rotationSpeed: (Math.random() - 0.5) * 0.1
                });

                lastSpawnTime = timestamp;
                // 逐渐增加游戏难度
                gameSpeed += SPEED_INCREASE;
            }
        }

        // 更新物品位置
        function updateItems() {
            for (let i = items.length - 1; i >= 0; i--) {
                const item = items[i];
                item.y += item.speed;
                item.rotation += item.rotationSpeed;

                // 检查是否接住物品
                if (checkCollision(item)) {
                    if (item.type === 'bomb') {
                        endGame();
                        return;
                    } else {
                        score += 10;
                        document.getElementById('score').textContent = `分数: ${score}`;
                        items.splice(i, 1);
                        // 添加得分动画
                        addScorePopup(item.x + ITEM_SIZE/2, item.y + ITEM_SIZE/2);
                    }
                }
                // 检查物品是否掉落到底部
                else if (item.y > GAME_HEIGHT) {
                    if (item.type !== 'bomb') {
                        // 错过水果，扣分
                        score = Math.max(0, score - 5);
                        document.getElementById('score').textContent = `分数: ${score}`;
                    }
                    items.splice(i, 1);
                }
            }
        }

        // 碰撞检测
        function checkCollision(item) {
            return (
                item.y + ITEM_SIZE > basketY &&
                item.y < basketY + BASKET_HEIGHT &&
                item.x + ITEM_SIZE > basketX &&
                item.x < basketX + BASKET_WIDTH
            );
        }

        // 添加得分弹窗
        function addScorePopup(x, y) {
            const popup = document.createElement('div');
            popup.textContent = '+10';
            popup.style.position = 'absolute';
            popup.style.left = `${x}px`;
            popup.style.top = `${y}px`;
            popup.style.color = '#fff';
            popup.style.textShadow = '0 2px 4px rgba(0,0,0,0.3)';
            popup.style.fontSize = '20px';
            popup.style.transition = 'all 0.5s ease-out';
            popup.style.pointerEvents = 'none';
            popup.style.transform = 'translate(-50%, -50%)';
            document.getElementById('gameContainer').appendChild(popup);

            // 动画效果
            setTimeout(() => {
                popup.style.opacity = '0';
                popup.style.transform = 'translate(-50%, -100%)';
                setTimeout(() => popup.remove(), 500);
            }, 10);
        }

        // 结束游戏
        function endGame() {
            gameOver = true;
            document.getElementById('finalScore').textContent = `最终分数: ${score}`;
            document.getElementById('gameOver').style.display = 'block';
        }

        // 重置游戏
        function resetGame() {
            score = 0;
            gameSpeed = INITIAL_SPEED;
            items = [];
            basketX = GAME_WIDTH / 2 - BASKET_WIDTH / 2;
            gameOver = false;
            lastSpawnTime = 0;
            document.getElementById('score').textContent = `分数: ${score}`;
            document.getElementById('gameOver').style.display = 'none';
            requestAnimationFrame(gameLoop);
        }

        // 绘制游戏
        function draw() {
            // 清空画布
            ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);

            // 绘制天空背景
            const gradient = ctx.createLinearGradient(0, 0, 0, GAME_HEIGHT);
            gradient.addColorStop(0, '#87CEEB');
            gradient.addColorStop(1, '#B0E2FF');
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);

            // 绘制地面
            ctx.fillStyle = '#7CFC00';
            ctx.fillRect(0, GAME_HEIGHT - 20, GAME_WIDTH, 20);

            // 绘制篮子
            ctx.drawImage(IMAGES.basket, basketX, basketY, BASKET_WIDTH, BASKET_HEIGHT);

            // 绘制物品
            items.forEach(item => {
                ctx.save();
                ctx.translate(item.x + ITEM_SIZE/2, item.y + ITEM_SIZE/2);
                ctx.rotate(item.rotation);
                ctx.drawImage(IMAGES[item.type], -ITEM_SIZE/2, -ITEM_SIZE/2, ITEM_SIZE, ITEM_SIZE);
                ctx.restore();
            });
        }

        // 游戏循环
        function gameLoop(timestamp) {
            if (!timestamp) timestamp = 0;
            if (!gameOver) {
                spawnItem(timestamp);
                updateItems();
                draw();
                requestAnimationFrame(gameLoop);
            }
        }

        // 初始化游戏
        async function init() {
            initCanvas();
            await loadImages();
            initEvents();
            resetGame();
        }

        // 启动游戏
        init();
    })();
</script>
</body>
</html>